package cn.itcast.httpclient;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

/**
 * 演示：使用HttpClient的连接池管理连接
 */
public class HttpConnectManager {

	public static void main(String[] args) throws Exception {
		// 初始化连接池管理器对象
		PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
		// 设置最大连接数
		cm.setMaxTotal(200);
		// 设置每个主机地址的并发数
		cm.setDefaultMaxPerRoute(20);

		// 构建请求配置信息
		RequestConfig config = RequestConfig.custom().setConnectTimeout(1000) // 创建连接的最长时间
				.setConnectionRequestTimeout(500) // 从连接池中获取到连接的最长时间
				.setSocketTimeout(10 * 1000) // 数据传输的最长时间
				.setStaleConnectionCheckEnabled(true) // 提交请求前测试连接是否可用
				.build();

		// 构建HttpClient对象,把连接池、请求配置对象作为参数
		CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(config)
				.build();

		doGet(httpClient);
		System.out.println("=============");
//		doGet(httpClient);
	}

	public static void doGet(CloseableHttpClient httpClient) throws Exception {

		HttpGet httpGet = new HttpGet("http://www.baidu.com/");

		String result = httpClient.execute(httpGet, new BasicResponseHandler());
		System.out.println(result);
		// 此处不能关闭httpClient，如果关闭httpClient，连接池也会销毁
		// httpclient.close();
	}

}
